import React, { useRef } from 'react'
import { useAppDispatch, useAppSelector } from '../../hooks'
import { IUser } from '../../models/types'
import { RootState } from '../../store'
import { addUserActon } from '../../store/reducers/person'

export default function Person() {
  const { count } = useAppSelector((state: RootState) => state.count)
  const { users } = useAppSelector((state: RootState) => state.persons)
  const dispatch = useAppDispatch()
  const nameRef = useRef<HTMLInputElement | null>(null)
  const ageRef = useRef<HTMLInputElement | null>(null)

  const addPerson = () => {
		const personObj: IUser = {
      id: Math.floor(Math.random() * 100000).toString(),
      name: nameRef.current?.value || '',
      age: Number(ageRef.current?.value)
    }
    dispatch(addUserActon(personObj))
    nameRef.current!.value = ''
    ageRef.current!.value = ''
  }
  
  return (
    <div>
      <h2>我是Person组件,上方组件求和为：{count}</h2>
      <input ref={nameRef} type="text" placeholder="输入名字"/>
      <input ref={ageRef} type="text" placeholder="输入年龄"/>
      <button onClick={addPerson}>添加</button>
      <ul>
        {
          users.map((p)=>{
            return <li key={p.id}>{p.name}--{p.age}</li>
          })
        }
      </ul>
    </div>
  )
}
